using UnityEngine;
using Utility.GameEvents.Core;

namespace Utility.GameEvents.Examples {
    public class AudioSystem : MonoBehaviour, IGameEventListener<EnemyDefeatedEvent>, IGameEventListener<GamePausedEvent>, IGameEventListener<GameResumedEvent> {
        [Header("AudioSource Reference")]
        [SerializeField] private AudioSource _audioSource;

        [Header("Audio clips")] 
        [Tooltip("Play this sound on a enemy defeated."),SerializeField] private AudioClip _enemyDefeatedSound;
        [Tooltip("Play this sound on game paused."), SerializeField] private AudioClip _gamePausedSound;
        [Tooltip("Play this sound on game resumed."), SerializeField] private AudioClip _gameResumedSound;

        private void Awake() {
            if (_audioSource) return;
            if (!TryGetComponent<AudioSource>(out _audioSource)) {
                _audioSource = gameObject.AddComponent<AudioSource>();
            }
        }
        
        private void OnEnable() {
            EventBus.Register<EnemyDefeatedEvent>(this);
            EventBus.Register<GamePausedEvent>(this);
            EventBus.Register<GameResumedEvent>(this);
        }

        private void OnDisable() {
            EventBus.Unregister<EnemyDefeatedEvent>(this);
            EventBus.Unregister<GamePausedEvent>(this);
            EventBus.Unregister<GameResumedEvent>(this);
        }

        private void playOneShot(AudioClip clip) {
            if(clip &&  _audioSource) {
                _audioSource.PlayOneShot(clip);
            }
        }
        
        public void OnEventRaised(EnemyDefeatedEvent gameEvent) {
            playOneShot(_enemyDefeatedSound);
        }

        public void OnEventRaised(GamePausedEvent gameEvent) {
            playOneShot(_gamePausedSound);
        }

        public void OnEventRaised(GameResumedEvent gameEvent) {
            playOneShot(_gameResumedSound);
        }
    }
}